<template>
  <div class="basic_info">
    <div class="reset">
      <div class="resetInfo" v-if="!yearShow">
        <div class="title">升级用户数</div>
        <div class="content">
          <div class="content-title">产品模块：</div>
          <div class="content-items">
            <div class="item-div-1">
              <div class="item-text-1" style="color: #1b94fb">象过河云进销存</div>
              <div class="item-text-2" style="color: #1b94fb">
                {{ bookModel.version || '标准财务版' }}
              </div>
            </div>
          </div>
        </div>
        <div class="user-number">
          <div style="display: flex; align-items: center">
            <div class="user-title">用户数：</div>
            <button class="reduce-add" @click="clickReduce">-</button>
            <input class="number-input" v-model="thUserCount" disabled />
            <button class="reduce-add" style="margin-left: -1px" @click="clickAdd">+</button>
          </div>
        </div>
        <div style="display: flex; align-items: center; justify-content: space-between; width: 720px">
          <div class="pay-price">
            <div class="user-title">价格：</div>
            <div class="after-price">￥{{ accountPrice.toFixed(2) }}</div>
            <img style="margin-left: 20px; width: 20px; height: 20px" src="./desc.png" @click="priceDesc" />
            <!-- <div class="user-title" style="margin-left: 30px; min-width: 40px;">原价：</div>
                        <div class="before-price">￥{{ (priceModel.originalPrice || 0).toFixed(2) }}</div> -->
          </div>
          <!-- <el-button size="mini" @click="yearShow = true">按年购买</el-button> -->
        </div>
        <!-- <img style="width: 720px; height: 225px;" src="./thgm.png" /> -->
        <div class="resetBtn">
          <el-button size="mini" class="pay-btn" @click="calculateUserNum">立即支付</el-button>
        </div>
      </div>
      <div class="resetInfo" v-else>
        <div class="title">账套购买</div>
        <div class="content content-show">
          <div class="content-title">产品模块：</div>
          <div class="content-items">
            <div v-for="(item, index) in versionList" :key="index" @click="selectVersion(item, index)">
              <div :class="current == index ? 'item-div-1' : 'item-div-2'">
                <div class="item-text-1" :style="{ color: current == index ? '#1B94FB' : '#999999' }">
                  象过河云进销存
                </div>
                <div class="item-text-2" :style="{ color: current == index ? '#1B94FB' : '#999999' }">
                  {{ item.name }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="user-number user-number-show">
          <div style="display: flex; align-items: center"  v-if="(versionList[current] || {}).name == '必用版'">
            <div class="user-title">用户数：</div>
            <div style="font-weight: 500;line-height: 36px;">不限</div>  
          </div>
          <div style="display: flex; align-items: center" v-else>
            <div class="user-title">用户数：</div>
            <div
              class="user-div"
              v-for="(item, index) in userIndex"
              :key="item.title"
            >
              {{ userList[index].title }}
            </div>
            <div
              :class="index == userSelect ? 'select-btn select-btn-on' : 'select-btn'"
              v-for="(item, index) in userList.length - userIndex"
              :key="item.title"
              @click="clickUserNumber(index)"
            >
              {{ userList[index + userIndex].title }}
            </div>
            <div @click="moreUser" v-if="!(versionList.length > current && versionList[current].name === '专业版')">更多用户</div>
          </div>
          <div style="display: flex; align-items: center; margin-top: 30px">
            <div class="user-title">使用年限：</div>
            <div class="user-div" style="width: max-content;">{{ getFormatDays() }}</div>
            <!-- <div class="user-div">{{ yearList[yearIndex].no }}年</div> -->
          </div>
        </div>
        <div class="pay-price content-show"  v-if="accountPrice > 0">
          <div class="user-title">价格：</div>
          <div class="after-price-show">￥{{ accountPrice.toFixed(2) }}</div>
          <img style="margin-left: 20px; width: 20px; height: 20px" src="./desc.png" @click="calcDesc" />
          <!-- <div class="user-title" style="margin-left: 30px; min-width: 40px;">原价：</div>
                    <div class="before-price">￥{{ (priceModel.originalPrice || 0).toFixed(2) }}</div> -->
        </div>
        <div class="resetBtn" v-if="accountPrice > 0">
          <el-button size="mini" class="pay-btn" @click="calculateUserNum">立即支付</el-button>
        </div>
        <div class="account-info" v-if="accountPrice <= 0">{{ periodOfUseMsg }}</div>
      </div>
    </div>
    <popupPriceDesc ref="priceDesc"></popupPriceDesc>
    <popupMoreDesc ref="moreDesc" :title="moreTitle" :desc="moreDesc" :desc1="moreDesc1"></popupMoreDesc>
    <dialogStaff ref="dialogStaff" @onSelectStaff="onSelectStaff"></dialogStaff>
  </div>
</template>

<script>
import popupPriceDesc from '../../components/popupPriceDesc'
import popupMoreDesc from '../../components/popupMoreDesc'
import dialogStaff from '@/views/components/dialogStaff'
import { postAction, getAction } from '@/api/manage'
import { USER_INFO, ACCOUNT_BOOK } from '@/store/mutation-types'
import Vue from 'vue'
export default {
  name: 'upgradeUserNo',
  components: {
    popupPriceDesc,
    popupMoreDesc,
    dialogStaff
  },
  data() {
    return {
      yearShow: true,
      moreTitle: '',
      moreDesc: '',
      moreDesc1: '',
      current: 0, // 版本列表下标
      priceIndex: 0, // 价格列表下标
      priceList: [], // 价格列表数据
      priceModel: {}, // 价格model
      versionList: [], // 版本列表
      url: {
        queryList: '/XghAuthorizationCenter/xghAuthorizationCenterPrice/queryList',
        addOrder: '/XghAuthorizationCenter/xghAuthorizationCenterOrders/add',
      },
      // 特惠用户数
      thUserCount: 1,
      thPrice: 0.01,
      // 用户数实际下标 userIndex + userSelect
      userCount: 0, // 账套用户数
      userIndex: 0, // 账套用户数对应的用户下标
      userSelect: 0, // 用户列表选中的下标
      userList: [
        { title: '1用户', no: 1 },
        { title: '2用户', no: 2 },
        { title: '3用户', no: 3 },
        { title: '4用户', no: 4 },
        { title: '5用户', no: 5 },
        { title: '6用户', no: 6 },
        { title: '7-12用户', no: 7 },
        { title: '13-20用户', no: 13 },
      ], // 用户数列表
      yearIndex: 0, // 年限下标
      yearList: [
        { title: '1年', no: 1 },
        { title: '2年', no: 2 },
        { title: '3年', no: 3 },
        { title: '4年', no: 4 },
        { title: '5年', no: 5 },
      ], // 使用年限列表
      buyType: 1, // 购买类型
      bookModel: {}, // 账套信息
      orderModel: {}, // 订单信息
      accountPrice: 0, // 账套价格
      periodOfUseMsg: '',
      selectedStaffList: [], // 存储选中的员工列表
      currentUserCount: 0, // 当前用户数量
    }
  },
  async created() {
    let res = await getAction(this.url.queryList)
    if (res.code == 200) {
      this.versionList = res.result || []
    }
    this.getUserCount()
    this.getCurrentUserCount() // 获取当前用户数量
  },
  computed: {
    // // 逻辑计算
    // calcUserPrice() {
    //     if (this.bookModel.remainingDays <= 0) return 0
    //     if (!this.versionList || this.versionList.length <= 0) return 0
    //     this.versionList.forEach(item => {
    //         if (item.id == this.orderModel.goodsId) {
    //             this.priceList = item.priceBatchList
    //             this.priceList.forEach(el => {
    //                 if (el.cycle = this.orderModel.oldYearNum) {
    //                     this.priceModel = el
    //                 }
    //             })
    //         }
    //     })
    //     let lastDay = this.bookModel.remainingDays
    //     let upgradeNo = this.userList[this.userSelect + this.userIndex].no - this.userCount
    //     let price = upgradeNo * this.priceModel.price * lastDay / 365.0
    //     console.log(lastDay, upgradeNo, price)
    //     price = price.toFixed(2)
    //     return price
    // },
  },
  methods: {
    getFormatDays() {
       //已过期选几年是几年
       if (this.bookModel.remainingDays <= 0) {
        return '0年'
      }
      let year = parseInt(this.bookModel.remainingDays / 365)
      let day = this.bookModel.remainingDays % 365
      let result = ''
      if (year > 0) {
        result = year + '年'
      }
      if (day > 0) {
        result = result + `${day}天`
      }
      return result
    },
    // 获取账套信息
    getUserCount() {
      let accountId = ''
      if (this.$route.query.id) {
        accountId = this.$route.query.id
      } else {
        let accountBook = Vue.ls.get(ACCOUNT_BOOK)
        accountId = accountBook && accountBook.id
      }
      getAction('/XghAuthorizationCenter/xghAuthorizationCenterOrders/queryByAccountBookId', {
        xghAccountBookId: accountId,
      }).then((res) => {
        if (res.code === 200) {
          this.bookModel = res.result
          this.orderModel = res.result.xghAuthorizationCenterOrders || {}
          this.buyType = this.bookModel.buyType
          this.yearShow = this.buyType != 1
          this.userCount = this.bookModel.userNumber
          this.thUserCount = this.userCount// + 1
          
          if (this.bookModel.remainingDays < 0) {
            this.periodOfUseMsg = `您的账套到期时间：${this.bookModel.periodOfUse} 账套已过期：${-this.bookModel
              .remainingDays}天，请选择用户数或产品进行升级。`
          } else {
            this.periodOfUseMsg = `您的账套到期时间：${this.bookModel.periodOfUse} 剩余：${this.bookModel.remainingDays}天，请选择用户数或产品进行升级。`
          }

          if (this.bookModel.version) {
            this.current = this.versionList.findIndex(item => item.name == this.bookModel.version)
            // 根据版本设置用户列表
            if (this.bookModel.version === '专业版') {
              this.userList = [
                { title: '1用户', no: 1 },
                { title: '不限用户', no: 2147483647 }
              ]
            }else {
              this.userList = [
                { title: '1用户', no: 1 },
                { title: '2用户', no: 2 },
                { title: '3用户', no: 3 },
                { title: '4用户', no: 4 },
                { title: '5用户', no: 5 },
                { title: '6用户', no: 6 },
                { title: '7-12用户', no: 7 },
                { title: '13-20用户', no: 13 }
              ]
            }
          } else {
            this.current = this.versionList.length - 1
          }
          this.userIndexFromUserCount()
          if (this.bookModel.remainingDays > 0) {
            let num = this.bookModel.remainingDays / 365
            if (num > parseInt(num)) {
              this.yearIndex = parseInt(num)
            } else {
              this.yearIndex = parseInt(num) - 1
            }
          } else {
            this.yearIndex = 0
          }
          // 超出5年，按5年回显
          if (this.yearIndex > 4) {
            this.yearIndex = 4
          }
          // this.yearIndex = parseInt(this.bookModel.remainingDays / 365)
          this.calculateOrderPrice()
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    // 版本价格列表
    getVersionList() {
      getAction(this.url.queryList).then((res) => {
        if (res.code == 200) {
          this.versionList = res.result || []
        }
      })
    },
    // 版本选择
    selectVersion(item, index) {
      if (this.current != index) {
        let version = this.bookModel.version || '标准财务版'
        // 高版本不能买低版本
        if ((version == '高级版' && (item.name == '专业版' || item.name == '必用版')) || 
            (version == '专业版' && item.name == '必用版') || 
            (version == '标准财务版' && item.name != '标准财务版')) {
          return
        }
        // 保存切换前的状态
        const previousVersion = this.versionList[this.current].name
        const wasUnlimitedBefore = this.bookModel.userNumber > 100  // 判断是否是不限用户

        this.current = index
        // 根据版本设置用户列表
        if (item.name === '专业版') {
          this.userList = [
            { title: '1用户', no: 1 },
            { title: '不限用户', no: 2147483647 }
          ]
          // 切换到专业版时，总是重置选择状态
          this.userSelect = 0
          this.userIndex = 0
          // 如果之前是不限用户，则选择不限用户
          if (wasUnlimitedBefore) {
            this.userSelect = 0
            this.userIndex = 1
          }
        } else {
          this.userList = [
            { title: '1用户', no: 1 },
            { title: '2用户', no: 2 },
            { title: '3用户', no: 3 },
            { title: '4用户', no: 4 },
            { title: '5用户', no: 5 },
            { title: '6用户', no: 6 },
            { title: '7-12用户', no: 7 },
            { title: '13-20用户', no: 13 }
          ]
          // 从专业版切换到其他版本时，如果之前是不限用户，则选择1用户
          if (previousVersion === '专业版' && wasUnlimitedBefore) {
            this.userSelect = 0
            this.userIndex = 0
          }
        }
        this.calculateOrderPrice()
      }
    },
    // 计算价格
    calculateOrderPrice() {
      let accountId = ''
      if (this.$route.query.id) {
        accountId = this.$route.query.id
      } else {
        let accountBook = Vue.ls.get(ACCOUNT_BOOK)
        accountId = accountBook && accountBook.id
      }
      let v = this.versionList.length > this.current && this.versionList[this.current].name
      let index = this.userIndex == 7 ? this.userList.length - 1 : this.userIndex + this.userSelect
      let params = {
        buyType: this.yearShow ? '2' : '1',
        userNum: this.yearShow ? this.userList[index].no : this.thUserCount,
        xghAccountBookId: accountId,
        yearNum: this.yearShow ? this.yearList[this.yearIndex].no : 10,
        version: v,
        limitUser: v === '必用版' || (v === '专业版' && this.userList[index].title === '不限用户') ? false : true
      }
      postAction('/XghAuthorizationCenter/xghAuthorizationCenterOrders/calculateOrderPrice', params).then((res) => {
        if (res.code == 200) {
          this.accountPrice = res.result || 0
        } else {
          this.accountPrice = 0
        }
      })
    },
    // 减少
    clickReduce() {
      if (this.thUserCount <= this.userCount + 1) {
        this.$elMessage.warning('已经是最低用户数了！')
        return
      }
      this.thUserCount--
      this.calculateOrderPrice()
    },
    // 增加
    clickAdd() {
      this.thUserCount++
      this.calculateOrderPrice()
    },
    // 计算用户数并检查是否需要选择员工
    calculateUserNum() {
      let userNum = this.yearShow ? this.userList[this.userIndex + this.userSelect].no : this.thUserCount
      if (userNum == 7) {
        userNum = 12
      } else if (userNum == 13) {
        userNum = 20
      }

      // 判断选择的用户数是否小于当前用户数
      if (this.buyType && userNum < this.currentUserCount && userNum !== 2147483647) {
        // 如果是续费且选择的用户数小于当前用户数且不是不限用户，则弹出选择用户弹窗
        this.openStaffDialog()
      } else {
        // 用户数没有超出，直接执行支付流程
        this.gotoPay()
      }
    },

    // 立即支付
    gotoPay() {
      let accountId = ''
      if (this.$route.query.id) {
        accountId = this.$route.query.id
      } else {
        let accountBook = Vue.ls.get(ACCOUNT_BOOK)
        accountId = accountBook && accountBook.id
      }
      let userNum = 0
      // let yearNum = 0
      let userNumBack = ''
      if (this.yearShow) {
        userNum = this.userList[this.userIndex + this.userSelect].no
        userNumBack = this.userList[this.userIndex + this.userSelect].title
        if (userNum == 7) {
          userNum = 12
        } else if (userNum == 13) {
          userNum = 20
        }
        // userNum -= this.userCount
      } else {
        userNum = this.thUserCount
        userNumBack = this.thUserCount + '用户'
      }
      let model = this.versionList[this.current]
      let params = {
        goodsId: model.id,
        goodsName: model.name,
        goodsNumber: 1,
        goodsType: '1',
        orderMoney: this.accountPrice.toFixed(2),
        // orderMoney: 0.01,
        xghAccountBookId: accountId,
        buyType: this.yearShow ? '2' : '1',
        oldYearNum: this.yearShow ? parseInt(this.bookModel.remainingDays / 365) + 1 : 10,
        userNum,
        // yearNum, // 升级用户数不传该参数
        userNumBack,
        showData: this.getFormatDays(),
      }
      // console.log(JSON.stringify(params))
      // debugger
      postAction(this.url.addOrder, params).then((res) => {
        if (res.code == 200) {
          this.$router.push({
            path: '/setting/buy/confirmPay',
            query: {
              id: res.result.id,
            },
          })
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    // 用户数转用户下标
    userIndexFromUserCount() {
      if (this.userCount > 0 && this.userCount < 7) {
        this.userIndex = this.userCount - 1
      } else if (this.userCount >= 7 && this.userCount < 13) {
        this.userIndex = 7 - 1
      } else if (this.userCount >= 13 && this.userCount <= 20) {
        this.userIndex = 8 - 1
      } else {
        this.userIndex = 1
      }
    },
    // 选择用户数
    clickUserNumber(index) {
      this.userSelect = index
      this.calculateOrderPrice()
    },
    // 选择使用年限
    clickUseYear(index) {
      this.yearIndex = index
    },
    // 价格说明
    priceDesc() {
      this.$refs.priceDesc.dialogVisible = true
    },
    // 更多用户
    moreUser() {
      this.moreTitle = '更多用户'
      this.moreDesc = '尊敬的老板，您的大手笔购买，请直接联系客服：400-600-1168，会有更多优惠~'
      this.moreDesc1 = ''
      this.$refs.moreDesc.dialogVisible = true
    },
    // 计算说明
    calcDesc() {
      this.moreTitle = '说明'
      this.moreDesc = '增加用户数量价格计算：'
      this.moreDesc1 = '（选择增加后的用户数-已购买用户数）*（1年账套选择用户价格/365*账套到期可用天数）'
      this.$refs.moreDesc.dialogVisible = true
    },
    // 获取当前账套用户数量
    getCurrentUserCount() {
      getAction('/dept/xghAccountBookDept/getDeptUsers', {
        pageSize: 100000000,
        pageNo: 1,
      }).then((res) => {
        if (res.code === 200) {
          this.currentUserCount = res.result.total || 0
        }
      })
    },
    // 打开选择员工弹框
    openStaffDialog() {
      let userNum = this.yearShow ? this.userList[this.userIndex + this.userSelect].no : this.thUserCount
      if (userNum == 7) {
        userNum = 12
      } else if (userNum == 13) {
        userNum = 20
      }
      this.$refs.dialogStaff.title = `选择${userNum}个保留用户`
      this.$refs.dialogStaff.maxSelectCount = userNum
      this.$refs.dialogStaff.defaultSelectedType = true
      this.$refs.dialogStaff.dialogVisible = true
    },
    // 员工选择回调
    async onSelectStaff(selectedStaff) {
      this.selectedStaffList = selectedStaff
      
      // 调用保留用户接口
      let accountBook = Vue.ls.get(ACCOUNT_BOOK)
      let accountId = accountBook && accountBook.id

      try {
        const res = await getAction('/dept/xghAccountBookDept/saveUsers', {
          ids: selectedStaff.map(staff => staff.id).join(','),
          accountBookId: accountId
        })
        
        if (res.code === 200) {
          // 保存成功后执行支付流程
          this.gotoPay()
        } else {
          this.$elMessage.error(res.message || '保存用户失败')
        }
      } catch (error) {
        this.$elMessage.error('保存用户失败')
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.basic_info {
  width: 100%;
  height: calc(100vh - 1.875117rem);
  background: #f0f2f5;
  box-sizing: border-box;
  padding: 0 0.168761rem 0.168761rem;
  display: flex;
  flex-direction: column;
}

.reset {
  background-color: #fff;
  height: 100%;

  .resetInfo {
    padding: 0.375023rem;

    .title {
      border-bottom: 1px solid #eee;
      font-size: 16px;
      font-family: PingFang SC;
      font-weight: 600;
      color: #1b94fb;
      padding-bottom: 13px;
    }

    .content {
      // border-bottom: 1px solid #eee;
      padding-bottom: 28px;
      display: flex;
    }

    .content-show {
      padding-bottom: 25px;
      border-bottom: 1px solid #eee;
    }

    .content-title {
      margin-top: 31px;
      min-width: 72px;
      height: 18px;
      line-height: 18px;
      font-size: 13px;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
    }

    .content-items {
      display: flex;
      flex-wrap: wrap;
    }

    .item-div-1 {
      margin-top: 20px;
      margin-right: 20px;
      width: 171px;
      height: 103px;
      background-image: url('./v_selected.png');
      background-repeat: no-repeat;
      background-size: 171px 103px;
    }

    .item-div-2 {
      margin-top: 20px;
      margin-right: 20px;
      width: 171px;
      height: 103px;
      background-image: url('./v_unselect.png');
      background-repeat: no-repeat;
      background-size: 171px 103px;
    }

    .item-text-1 {
      padding: 26px 26px 0 26px;
      font-size: 16px;
      font-family: PingFang SC-Semibold, PingFang SC;
      font-weight: 600;
      color: #999999;
      line-height: 30px;
    }

    .item-text-2 {
      padding: 0 26px;
      font-size: 16px;
      font-family: PingFang SC-Semibold, PingFang SC;
      font-weight: 600;
      color: #999999;
      line-height: 30px;
    }

    .user-number {
      // padding: 35px 0;
      // border-bottom: 1px solid #eee;
    }

    .user-number-show {
      padding: 26px 0;
      border-bottom: 1px solid #eee;
    }

    .user-title {
      min-width: 72px;
      height: 18px;
      line-height: 18px;
      font-size: 13px;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
    }

    .user-div {
      margin-right: 20px;
      width: 77px;
      height: 36px;
      text-align: center;
      line-height: 36px;
      color: #666666;
    }

    .user-div-on {
      color: #1b94fb;
    }

    .select-btn {
      margin-right: 20px;
      width: 77px;
      height: 36px;
      text-align: center;
      line-height: 30px;
      border-radius: 5px;
      background-image: url('./btn_off.png');
      background-repeat: no-repeat;
      background-size: 77px 36px;
      line-height: 36px;
      font-size: 14px;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
    }

    .select-btn-on {
      background-image: url('./btn_on.png');
    }

    .reduce-add {
      width: 34px;
      height: 34px;
      border: 1px solid #cbced3;
      font-size: 20px;
      color: #cbced3;
      background-color: #ffffff;
    }

    .number-input {
      margin-left: -1px;
      width: 69px;
      height: 34px;
      background: #ffffff;
      border: 1px solid #cbced3;
      text-align: center;
      font-size: 16px;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
    }

    .number-input:focus {
      outline: none;
    }

    .pay-price {
      display: flex;
      align-items: center;
      padding: 25px 0;
      // border-bottom: 1px solid #eee;
    }

    .after-price {
      height: 32px;
      font-size: 25px;
      font-family: Helvetica Neue-Bold, Helvetica Neue;
      font-weight: bold;
      color: #000000;
      line-height: 32px;
    }

    .after-price-show {
      height: 32px;
      font-size: 25px;
      font-family: Helvetica Neue-Bold, Helvetica Neue;
      font-weight: bold;
      color: #fd6c21;
      line-height: 32px;
    }

    .before-price {
      font-size: 20px;
      font-family: HelveticaNeue-, HelveticaNeue;
      font-weight: normal;
      color: #666666;
      line-height: 32px;
      text-decoration: line-through;
    }
  }
}

.resetBtn {
  margin-top: 28px;
}

.pay-btn {
  width: 103px;
  height: 35px;
  background: #1993fb;
  font-size: 13px;
  font-family: PingFang SC-Medium, PingFang SC;
  font-weight: 500;
  color: #ffffff;
}
.account-info {
      margin-top: 28px;
      font-size: 14px;
      font-family: PingFang SC-Semibold, PingFang SC;
      font-weight: 600;
      color: #ff820d;
      line-height: 32px;
    }
</style>
